package org.example.server.service.impl;

import com.google.zxing.WriterException;

import org.example.common.exception.CertNoException;
import org.example.common.exception.MobileException;
import org.example.common.exception.PatientNOTException;
import org.example.common.utils.QrCodeUtil;
import org.example.dto.HospitalNoDDTO;
import org.example.dto.PatientDTO;
import org.example.dto.PatientUDTO;
import org.example.entity.PatientInfo;
import org.example.entity.User;
import org.example.server.mapper.PatientMapper;
import org.example.server.mapper.UserMapper;
import org.example.server.service.PatientService;
import org.example.vo.AUPatientVO;
import org.example.vo.PatientDVO;
import org.example.vo.PatientVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class PatientServiceImpl implements PatientService {
    @Resource
    private PatientMapper patientMapper;
    @Resource
    private UserMapper userMapper;
    //    @Resource
//    private QrCodeUtil qrCodeUtil;
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
    private static final String ID_CARD_REGEX_18 = "^\\d{17}[\\dXx]$";


    @Override
    public List<PatientVO> select(String hospitalNo) {
        List<User> userList = userMapper.selectByHospitalNo(hospitalNo);

        List<PatientVO> patientVOList = new ArrayList<>();

        userList.forEach(user -> {
            List<PatientInfo> patientInfoList = patientMapper.selectByUserId(user.getUserId());
            patientInfoList.forEach(patientInfo -> {
                PatientVO patientVO = new PatientVO();
                patientVO.setPatientId(patientInfo.getPatientId());
                patientVO.setPatientName(patientInfo.getPatientName());
                patientVO.setPatientNo(patientInfo.getPatientNo());
                patientVOList.add(patientVO);
            });
        });
        return patientVOList;
    }

    @Override
    public PatientDVO selectByD(HospitalNoDDTO hospitalNoDDTO) throws WriterException, IOException {
        String patientId = hospitalNoDDTO.getPatientId();


        String qrCode = QrCodeUtil.generateQrCodeBase64(patientId);
        String barCode = QrCodeUtil.generateBarCodeBase64(patientId);


        PatientInfo patientInfo = patientMapper.selectByPatientId(patientId);
        if (patientInfo == null) {
            throw new PatientNOTException("该患者不存在");
        }
        PatientDVO patientDVO = PatientDVO.builder().
                patientId(patientInfo.getPatientId()).
                patientName(patientInfo.getPatientName()).
                patientNo(patientInfo.getPatientNo()).
                certNo(patientInfo.getCertNo()).
                address(patientInfo.getAddress()).
                barCode(barCode).          //    就诊号条形码
                        qrCode(qrCode).           //就诊号二维码
                        build();
        return patientDVO;
    }

    @Override
    public AUPatientVO insert(PatientDTO patientDTO) {

        extracted(patientDTO.getMobile(), patientDTO.getCertNo());

         String userId=userMapper.getByMobile(patientDTO.getMobile());

         String idCard=patientDTO.getCertNo();
        // 提取出生日期
        String birthDateStr = idCard.substring(6, 14);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);

        // 计算年龄
        LocalDate currentDate = LocalDate.now();
        int age = Period.between(birthDate, currentDate).getYears();

        // 确定性别
        String genderCode = idCard.substring(16, 17);
        String gender = Integer.parseInt(genderCode) % 2 == 1 ? "F" : "M";


        //患者号：截取身份证后六位字符
        String patientNo = patientDTO.getCertNo().substring(patientDTO.getCertNo().length() - 6);
        PatientInfo patientInfo = PatientInfo.builder().
                userId(userId).

                patientName(patientDTO.getPatientName()).
                certNo(patientDTO.getCertNo()).
                patientNo(patientNo).
                mobile(patientDTO.getMobile()).
                status(1).
                patientId("1").
                sex(gender).//TODO 性别
                age(age).
                address(patientDTO.getAddress()).
                createTime(new Date()).
                updateTime(new Date()).
                build();
        patientMapper.insert(patientInfo);
        String patientId = String.valueOf(patientInfo.getId());
        patientInfo.setPatientId(patientId);
        patientMapper.updatePatientId(patientInfo);
        AUPatientVO AUPatientVO = new AUPatientVO();
        AUPatientVO.setPatientId(patientId);
        return AUPatientVO;
    }


    @Override
    public void update(PatientUDTO patientUDTO) {

        extracted(patientUDTO.getMobile(), patientUDTO.getCertNo());

        PatientInfo patientInfo = new PatientInfo();
        BeanUtils.copyProperties(patientUDTO, patientInfo);
        patientMapper.update(patientInfo);
    }


    private static void extracted(String mobile, String certNo) {

        if (!mobile.matches(PHONE_REGEX)) {
            throw new MobileException("手机号格式不正确");
        }
        if (!certNo.matches(ID_CARD_REGEX_18)) {
            throw new CertNoException("身份证号格式不正确");
        }
    }

}
